package com.zhiyu.controller;

import com.zhiyu.common.ApiReturn;
import com.zhiyu.pojo.ShoppingCar;
import com.zhiyu.service.ShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RequestMapping("shoppingCar")
@Controller
@CrossOrigin
public class ShoppingCarController {

    @Autowired
    private ShoppingCarService shoppingCarService;

    //加入购物车
    @RequestMapping("add")
    @ResponseBody
    public ApiReturn add(ShoppingCar shoppingCar, HttpServletRequest request, HttpServletResponse response){
        String userInfo = (String) request.getSession().getAttribute("userInfo");
        if (userInfo==null||userInfo.equals("")){
            return ApiReturn.error("未登录");
        }
        String[] userStr = userInfo.split(":");
        shoppingCar.setUserId(Integer.valueOf(userStr[0]));
        int count = shoppingCarService.insert(shoppingCar);
        if (count<1){
            return ApiReturn.error("加入购物车失败");
        }
        return ApiReturn.success("加入购物车成功");
    }

    //获取该用户购物车
    @GetMapping("list/{userId}")
    @ResponseBody
    public ApiReturn list(@PathVariable("userId")int userId, HttpServletRequest request, HttpServletResponse response){
        ShoppingCar shoppingCar = new ShoppingCar();
        shoppingCar.setUserId(userId);
        List<ShoppingCar> shoppingCarList = shoppingCarService.findList(shoppingCar);
        if (shoppingCarList!=null&&shoppingCarList.size()>0){
            return ApiReturn.success("返回购物车数据",shoppingCarList);
        }
        return ApiReturn.error("无数据");
    }

    //删除
    @RequestMapping("delete")
    @ResponseBody
    public ApiReturn delete(ShoppingCar shoppingCar){
        int count = shoppingCarService.delete(shoppingCar);
        if (count<1){
            return ApiReturn.error("删除购物车商品失败");
        }
        return ApiReturn.success("删除购物车商品成功");
    }

    //修改
    @RequestMapping("update")
    @ResponseBody
    public ApiReturn update(ShoppingCar shoppingCar){
        int count = shoppingCarService.update(shoppingCar);
        if (count<1){
            return ApiReturn.error("修改购物车商品失败");
        }
        return ApiReturn.success("修改购物车商品成功");
    }
}
